package com.tengju.bff.interfaces.covercharge.util.redis;

import com.idanchuang.component.redis.config.DRedisLockConfig;
import com.idanchuang.component.redis.util.RedisUtil;

import java.util.concurrent.Callable;

/**
 * @author ：qumengmeng
 * @date ：Created in 2020/12/2 16:01
 * @description：防重用
 * @modified By：
 * @version: $
 */
public class HeavyUtil {

    public static <V> V runWithLock(String lockName, Callable<V> callable) throws Exception {
        if(!isRun(lockName)) {
            try {
                return callable.call();
            } catch (Exception e) {
                throw e;
            } finally {
                runDone(lockName);
            }
        }

        return null;
    }
    /**
     * 是否在运行,没运行自动设置为运行
     * 没运行则返回false并添加缓存
     * 运行中则返回true
     * @param key
     * @return
     */
    public static Boolean isRun(String key)
    {
        String get = RedisUtil.getInstance().get(key);
        if(get == null) {
            if(RedisUtil.getInstance().setIfAbsent(key, "1") ) {
                return false;
            }else {
                return true;
            }
        } else {
            return true;
        }
    }

    /**
     * 是否在运行-有过期时间版本
     * @param key
     * @param expire 毫秒
     * @return
     */
    public static Boolean isRun(String key, Integer expire)
    {
        String get = RedisUtil.getInstance().get(key);
        if(get == null) {
            if(RedisUtil.getInstance().setIfAbsent(key, "1") ) {
                RedisUtil.getInstance().expire(key, expire);
                return false;
            }else {
                return true;
            }
        } else {
            return true;
        }
    }

    /**
     * 运行结束
     * @param key
     * @return
     */
    public static Boolean runDone(String key)
    {
        String get = RedisUtil.getInstance().get(key);
        if(get == null) {
            return false;
        } else {
            RedisUtil.getInstance().del(key);
            return true;
        }
    }
}
